package co.edu.udem.dao.impl;

import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import co.edu.udem.dao.UserDao;
import co.edu.udem.domain.Authorities;
import co.edu.udem.domain.GroupMember;
import co.edu.udem.domain.User;

@Repository("userDao")
@Transactional
public class UserDaoImpl implements UserDao {
	
	
	private static final int STUDENT = 1;
	
	@Resource(name = "sessionFactory")
	private SessionFactory sessionFactory;

	@SuppressWarnings("unchecked")
	public List<User> getAllUsers() {
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("FROM  User");
		return query.list();
	}

	public User getUserById(String userCode) {
		Session session = sessionFactory.getCurrentSession();
		User person = (User) session.get(User.class, userCode);
		return person;
	}

	public void saveUser(User person) {
		Session session = sessionFactory.getCurrentSession();
		// Saves the person
		person.setEnabled(1);
		session.merge(person);

		//Saves the group member.
		GroupMember groupMember = new GroupMember();
		groupMember.setId(getLastGroupMemberId() + 1);
		groupMember.setGroupId(person.getUserType());
		groupMember.setUserName(person.getUserCode());
		session.merge(groupMember);
		
		Authorities auth = new Authorities();
		auth.setAuthority(person.getUserType() == STUDENT ? "ESTUDIANTE" : "PROFESOR");
		auth.setUserName(person.getUserCode());
		auth.setUuid(auth.getAuthority() + "-" + auth.getUserName());
		session.merge(auth);
	}

	private int getLastGroupMemberId() {
		Session session = sessionFactory.getCurrentSession();
		Query query = session
				.createQuery("Select MAX(gm.id) FROM  GroupMember gm ");
		return (Integer) query.uniqueResult();
	}

	public void deleteUser(String userCode) {
		Session session = sessionFactory.getCurrentSession();
		User person = (User) session.get(User.class, userCode);
		session.delete(person);
	}
}
